import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_give/pages/auth/auth_vm.dart';
import 'package:flutter_give/pages/tab_page.dart';
import 'package:flutter_give/utils/encrypt.dart';
import 'package:oktoast/oktoast.dart';
import 'package:rapid_kit/rapid_kit.dart';

import '../../common_ui/common_style.dart';
import '../../common_ui/loading.dart';
import '../../route/route_utils.dart';
import '../../route/routes.dart';
import '../../sample/configure/constants.dart';
import '../../theme.dart';
import '../../utils/LogUtils.dart';
import '../../utils/constants.dart';
import '../../utils/persistent_storage.dart';
import '../../utils/snack_tips.dart';
import '../../utils/sp_utils.dart';

/// 登录页面
class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return LoginPageState();
  }
}

class LoginPageState extends State<LoginPage> {
  AuthViewModel viewModel = AuthViewModel();
  static final GlobalKey<LoginPageState> globalKeyfour =
      GlobalKey<LoginPageState>();
  TextEditingController? inputConname;
  TextEditingController? inputConpass;

  // final TextEditingController _accountController =
  //     TextEditingController(text: "15220730439");
  // final TextEditingController _passwordController =
  //     TextEditingController(text: "5201314qaz.");

  final TextEditingController _accountController =
  TextEditingController(text: "");
  final TextEditingController _passwordController =
  TextEditingController(text: "");
  bool _obscureText = true;

  // 用户隐私协议
  bool _isAgreementChecked = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]);
    // inputConname = TextEditingController(text: "15200309617");
    // inputConpass = TextEditingController(text: "Rino123456..");
    // inputConname = TextEditingController(text: "15200309617");
    // inputConpass = TextEditingController(text: "Rino123456..");

    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFffffff),
      statusBarIconBrightness: Brightness.dark,
    ));

    _loadAgreementStatus();
  }

  // 二次加载
  void reloadData() {
    LogUtils.w("二次执行");
    _loadAgreementStatus();
  }

  Future<bool> _onAccessTokenAuth(String? accessToken) async {
    final authResp = await Authenticate.configure(accessToken ?? "");

    if (!mounted) return false;

    if (!authResp.success) {
      SnackTips.show(context,
          "Failed to authenticate: \n[${authResp.code}] ${authResp.message}");
      return false;
    } else {
      SharedPreferencesUtil.instance
          .setString(SampleConstants.storageKeyLoginToken, accessToken ?? "");
    }

    if (!mounted) return false;
    return true;
  }

  // 用户隐私协议
  void _loadAgreementStatus() async {
    final protocolAndPrivacy = await SharedPreferencesUtil.instance
        .getBool(SampleConstants.storageKeyAgreementPrivacyStatus);

    String? localAccount = await SharedPreferencesUtil.instance
        .getString(SampleConstants.storageKeyLoginAccount);
    LogUtils.w(localAccount);

    if ((localAccount ?? "").isNotEmpty) {
      _accountController.text = localAccount ?? "";
    }

    setState(() {
      LogUtils.e("用户隐私协议${protocolAndPrivacy}");
      // showToast("protocolAndPrivacy");
      _isAgreementChecked = protocolAndPrivacy == true;
    });
  }

  void onLogin() async {
    if (!_isAgreementChecked) {
      SnackTips.show(context, "请先阅读并同意用户协议和隐私政策");
      return;
    }

    final String account = _accountController.text;
    final String password = _passwordController.text;

    if (account.isEmpty) {
      SnackTips.show(context, "请输入账号");
      return;
    }

    if (password.isEmpty) {
      SnackTips.show(context, "请输入密码");
      return;
    }

    try {
      Loading.showLoading();

      if (!mounted) return;

      // 处理密码加密
      // 将字符串转换为UTF-8字节数组
      String passwordss = AESEncryption.encrypt(password);
      LogUtils.w(passwordss);

      viewModel.setLoginInfo(username: account, password: passwordss);
      viewModel.login().then((value) async => {
            if (value == true)
              {
                SharedPreferencesUtil.instance
                    .setString(SampleConstants.storageKeyLoginAccount, account),
                //  清空所有页面-跳转tab栏
                Loading.dismissAll(),
                showToast("登录成功"),
                SpUtils.saveString(Constants.SP_ZHSL_TABINDEX, "0"),
                RouteUtils.pushAndRemoveUntil(context, TabPage()),
              }
          });
    } catch (e) {
      Loading.dismissAll();
      LogUtils.e(e);
    }
  }

  // void onLogin() async {
  //   if (!_isAgreementChecked) {
  //     SnackTips.show(context, "请先阅读并同意用户协议和隐私政策");
  //     return;
  //   }
  //
  //   final String account = _accountController.text;
  //   final String password = _passwordController.text;
  //
  //   if (account.isEmpty) {
  //     SnackTips.show(context, "请输入账号");
  //     return;
  //   }
  //
  //   if (password.isEmpty) {
  //     SnackTips.show(context, "请输入密码");
  //     return;
  //   }
  //
  //   // CenterLoading.show(context);
  //
  //   // 犀云 - 存储实例
  //   final store = StoreProvider.of<AppState>(context);
  //   try {
  //     // // 犀牛-登录
  //     // RinoUser? user = await RinoSDK.user
  //     //     .loginWithAccount("15220730439", "5201314qaz", "86");
  //     // store.dispatch(LoggedAction(isLogin: true, user: user as RinoUser));
  //     // GlobalData.store.dispatch(updateHome());
  //     //
  //     // print("========犀云sdk===========$user");
  //     // LogUtils.d(user);
  //
  //     final loginResp = await AccountService.login("15218430349", "5201314qaz");
  //
  //     Loading.showLoading();
  //
  //     if (!mounted) return;
  //
  //     if (!loginResp.success) {
  //       SnackTips.show(context,
  //           "Failed to login: \n[${loginResp.code}] ${loginResp.message}");
  //       return;
  //     }
  //
  //     final authRet = await _onAccessTokenAuth(loginResp.data?.accessToken);
  //     if (!mounted) return;
  //
  //     if (authRet) {
  //       SharedPreferencesUtil.instance
  //           .setString(SampleConstants.storageKeyLoginAccount, "15218430349");
  //     }
  //
  //     viewModel.setLoginInfo(
  //         username: inputConname?.text, password: inputConpass?.text);
  //     viewModel.login().then((value) async => {
  //       print("===========================$inputConname"),
  //       print("===========================$inputConpass"),
  //       print("===========================${inputConname?.text}"),
  //       print("===========================${inputConpass?.text}"),
  //       if (value == true)
  //         {
  //           //  清空所有页面-跳转tab栏
  //           Loading.dismissAll(),
  //           showToast("登录成功"),
  //           RouteUtils.pushAndRemoveUntil(context, TabPage()),
  //         }
  //     });
  //   } catch (e) {
  //     Loading.dismissAll();
  //     LogUtils.e(e);
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    // 整个页面 - 包括顶部 底部
    return Scaffold(
      resizeToAvoidBottomInset: true,
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Container(
          // color: Colors.teal,
          padding: EdgeInsets.only(left: 20, right: 20),
          // 居中对齐
          alignment: Alignment.center,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SizedBox(height: 40),
              Container(
                alignment: Alignment.centerLeft, // 设置容器内容左对齐
                child: Text(
                  "欢迎回来!请登录",
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.w600,
                    fontFamily: "PingFang SC, PingFang SC",
                  ),
                ),
              ),
              Spacer(),
              Image.asset(
                "assets/app_img/ic_launch.png",
                width: 100,
                height: 100,
              ),
              // commonInput(labelText: "输入账号", controller: inputConname),
              Spacer(),
              ConstrainedBox(
                constraints: const BoxConstraints(maxWidth: 400.0),
                child: TextField(
                  style: _buildTextStyle(),
                  controller: _accountController,
                  decoration: _buildInputDecoration("手机号或邮箱"),
                  keyboardType: TextInputType.text,
                ),
              ),

              SizedBox(height: 15),
              // commonInput(
              //     labelText: "输入密码",
              //     obscureText: true,
              //     controller: inputConpass),
              ConstrainedBox(
                constraints: const BoxConstraints(maxWidth: 400.0),
                child: TextField(
                  style: _buildTextStyle(),
                  controller: _passwordController,
                  decoration: _buildPasswordInputDecoration("输入密码"),
                  keyboardType: TextInputType.text,
                  obscureText: _obscureText, // 设置密码是否可见
                ),
              ),
              const SizedBox(height: 15),
              _buildForgotPassword(),
              const SizedBox(height: 20),
              _buildLoginButton(),
              const SizedBox(height: 10),
              _buildAgreementCheckbox(),
              Spacer(),
              Spacer(),
              Spacer(),
              Spacer(),
              // 可选就要写onTap: () {}
              // wgiteBorderButton(
              //     title: "开始登录",
              //     onTap: () async {
              //       // if (value == true) {
              //     }),
              // SizedBox(height: 5),
              // // 必传写() {}
              // registerButton(() {
              //   RouteUtils.pushForNamed(context, RoutePath.registerPage);
              // })
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildLoginButton() {
    return SizedBox(
      width: 400, // 设置按钮宽度为400
      height: 45, // 设置按钮高度为40
      child: ElevatedButton(
        onPressed: onLogin,
        style: ElevatedButton.styleFrom(
          backgroundColor: SampleThemeConfigure.colorPrimary,
          foregroundColor: SampleThemeConfigure.colorForeground,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30),
          ),
          padding: const EdgeInsets.symmetric(horizontal: 80),
          // 调整水平内边距
          elevation: 0,
          shadowColor: Colors.transparent,
        ),
        child: const Text(
          '登录',
          style: TextStyle(fontSize: 18),
          textAlign: TextAlign.center, // 确保文字居中
        ),
      ),
    );
  }

  Widget _buildForgotPassword() {
    return ConstrainedBox(
      constraints: const BoxConstraints(maxWidth: 400.0),
      child: Row(
        // mainAxisAlignment: MainAxisAlignment.spaceBetween, // 左右布局
        children: [
          SizedBox(width: 10),
          GestureDetector(
            onTap: () {
              RouteUtils.pushForNamed(context, RoutePath.resetPassword);
            },
            child: const Text(
              '忘记密码',
              style: TextStyle(
                color: Color(0xFF1e1f22),
                // decoration: TextDecoration.underline,
                fontSize: 14,
              ),
            ),
          ),
          Spacer(),
          GestureDetector(
            onTap: () {
              RouteUtils.pushForNamed(context, RoutePath.registerPage);
            },
            child: const Text(
              '注册账号',
              style: TextStyle(
                color: Color(0xFF1e1f22),
                // decoration: TextDecoration.underline,
                fontSize: 14,
              ),
            ),
          ),
          SizedBox(width: 10),
        ],
      ),
    );
  }

  Widget _buildAgreementCheckbox() {
    return Center(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Theme(
            data: ThemeData(
              unselectedWidgetColor: SampleThemeConfigure.colorTextHint,
            ),
            child: Checkbox(
              value: _isAgreementChecked,
              onChanged: (bool? newValue) {
                setState(() {
                  _isAgreementChecked = newValue ?? false;
                });
                LogUtils.e("用户协议${newValue}");
                SharedPreferencesUtil.instance.setBool(
                    SampleConstants.storageKeyAgreementPrivacyStatus,
                    newValue ?? false);
              },
              checkColor: Colors.white,
              activeColor: SampleThemeConfigure.colorPrimary,
            ),
          ),
          const Text(
            "我已阅读并同意",
            style: TextStyle(
                color: SampleThemeConfigure.colorTextSub, fontSize: 12),
          ),
          InkWell(
            onTap: () {
              // Navigator.push(
              //   context,
              //   MaterialPageRoute(builder: (context) => UserProtocolPage()),
              // );
            },
            child: const Text(
              '《用户协议》',
              style: TextStyle(color: Color(0xFF00C888), fontSize: 12),
            ),
          ),
          const Text(
            "与",
            style: TextStyle(
                color: SampleThemeConfigure.colorTextSub, fontSize: 12),
          ),
          InkWell(
            onTap: () {
              // Navigator.push(
              //   context,
              //   MaterialPageRoute(builder: (context) => PrivacyPage()),
              // );
            },
            child: const Text(
              '《隐私政策》',
              style: TextStyle(color: Color(0xFF00C888), fontSize: 12),
            ),
          ),
        ],
      ),
    );
  }

  InputDecoration _buildInputDecoration(String hint) {
    return InputDecoration(
      hintText: hint,
      hintStyle: const TextStyle(
        color: SampleThemeConfigure.colorTextHint,
        fontSize: 16.0,
      ),
      contentPadding: const EdgeInsets.symmetric(horizontal: 20.0),
      filled: true,
      fillColor: SampleThemeConfigure.colorForeground,
      border: _buildOutlineInputBorder(),
      enabledBorder: _buildOutlineInputBorder(),
      focusedBorder: _buildOutlineInputBorder(),
    );
  }

  InputDecoration _buildPasswordInputDecoration(String hint) {
    return InputDecoration(
      hintText: hint,
      hintStyle: const TextStyle(
        color: SampleThemeConfigure.colorTextHint,
        fontSize: 16.0,
      ),
      contentPadding: const EdgeInsets.symmetric(horizontal: 20.0),
      filled: true,
      fillColor: SampleThemeConfigure.colorForeground,
      border: _buildOutlineInputBorder(),
      enabledBorder: _buildOutlineInputBorder(),
      focusedBorder: _buildOutlineInputBorder(),
      suffixIcon: IconButton(
        icon: Icon(
          _obscureText ? Icons.visibility : Icons.visibility_off,
          color: SampleThemeConfigure.colorTextHint,
        ),
        onPressed: () {
          setState(() {
            _obscureText = !_obscureText; // 切换密码的可见性
          });
        },
      ),
    );
  }

  OutlineInputBorder _buildOutlineInputBorder() {
    return OutlineInputBorder(
      borderRadius: BorderRadius.circular(15),
      borderSide: const BorderSide(color: Color(0xFFCCCCCC), width: 0.0),
    );
  }

  TextStyle _buildTextStyle() {
    return const TextStyle(
      fontSize: 16.0,
      color: Color(0xFF1e1f22),
    );
  }

  Widget registerButton(GestureTapCallback? onTap) {
    return GestureDetector(
        onTap: onTap,
        child: Container(
          alignment: Alignment.center,
          width: 180,
          height: 45,
          child: Text(
            "注册",
            style: TextStyle(color: Colors.white, fontSize: 15),
          ),
        ));
  }
}
